<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-03-31 21:45:00
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 21:45:00
 * @Description: 申请售后页面
-->
<template>
  <view class="container">
    <!-- 商品信息 -->
    <view class="product-card">
      <image :src="product.fruitImage" mode="aspectFill" class="product-image" />
      <view class="product-info">
        <text class="product-name">{{ product.fruitName }}</text>
        <text class="product-spec" v-if="product.specifications">{{ product.specifications }}</text>
        <view class="product-price-wrap">
          <text class="product-price">￥{{ product.price }}</text>
          <text class="product-quantity">x{{ product.quantity }}</text>
        </view>
      </view>
    </view>

    <!-- 申请表单 -->
    <view class="form-card">
      <!-- 退款金额 -->
      <view class="form-item">
        <text class="label required">退款金额</text>
        <view class="input-wrap">
          <text class="currency">￥</text>
          <input 
            type="digit" 
            v-model="form.refundAmount"
            :placeholder="'最多可退￥' + maxRefundAmount"
            class="input"
          />
        </view>
      </view>

      <!-- 退款原因 -->
      <view class="form-item">
        <text class="label required">退款原因</text>
        <view class="input-wrap" @click="showReasonPicker = true">
          <text :class="['reason-text', !form.reason && 'placeholder']">
            {{ form.reason || '请选择退款原因' }}
          </text>
          <u-icon name="arrow-right" color="#999" size="28"></u-icon>
        </view>
      </view>

      <!-- 问题描述 -->
      <view class="form-item">
        <text class="label required">问题描述</text>
        <textarea
          v-model="form.description"
          placeholder="请详细描述您遇到的问题，以便我们更好地为您服务"
          class="textarea"
          :maxlength="200"
        />
        <text class="word-count">{{ form.description.length }}/200</text>
      </view>

      <!-- 上传凭证 -->
      <view class="form-item">
        <text class="label">上传凭证</text>
        <view class="upload-wrap">
          <u-upload
            :file-list="form.images"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :max-count="6"
          >
            <view class="upload-button">
              <u-icon name="camera" size="48" color="#999"></u-icon>
              <text>上传图片</text>
            </view>
          </u-upload>
          <text class="upload-tip">最多上传6张图片，单张不超过5M</text>
        </view>
      </view>

      <!-- 联系方式 -->
      <view class="form-item">
        <text class="label required">联系方式</text>
        <input 
          type="number" 
          v-model="form.contact"
          placeholder="请输入手机号码"
          class="input"
        />
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-bar">
      <button 
        class="btn-submit" 
        :disabled="!isFormValid || submitting"
        @click="submitForm"
      >
        {{ submitting ? '提交中...' : '提交申请' }}
      </button>
    </view>

    <!-- 退款原因选择器 -->
    <u-picker
      v-model="showReasonPicker"
      :columns="[reasonOptions]"
      @confirm="onReasonConfirm"
    ></u-picker>
    
    <!-- 加载提示 -->
    <u-loading-page :loading="loading"></u-loading-page>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useOrderStore } from '../../store/orderStore.js'

// 创建store
const orderStore = useOrderStore()

// 商品信息
const product = ref({
  fruitId: 0,
  fruitName: '',
  specifications: '',
  price: 0,
  quantity: 0,
  fruitImage: '',
  orderNo: '',
  orderItemId: 0
})

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 最大可退金额
const maxRefundAmount = computed(() => {
  return (product.value.price * product.value.quantity).toFixed(2)
})

// 退款原因选项
const reasonOptions = [
  '商品质量问题',
  '商品与描述不符',
  '商品损坏',
  '商品数量不对',
  '收到商品与下单不符',
  '其他原因'
]

// 表单数据
const form = ref({
  refundAmount: '',
  reason: '',
  description: '',
  images: [],
  contact: ''
})

// 选择器显示状态
const showReasonPicker = ref(false)

// 表单验证
const isFormValid = computed(() => {
  return (
    form.value.refundAmount &&
    parseFloat(form.value.refundAmount) <= parseFloat(maxRefundAmount.value) &&
    form.value.reason &&
    form.value.description &&
    /^1[3-9]\d{9}$/.test(form.value.contact)
  )
})

// 页面加载
onLoad(async (options) => {
  if (options.orderNo) {
    loading.value = true
    try {
      // 获取订单详情
      const res = await orderStore.loadOrderDetail(options.orderNo)
      if (res && res.code === 200) {
        const order = orderStore.getCurrentOrder
        if (order && order.orderItems && order.orderItems.length > 0) {
          // 默认选中第一个商品
          const item = order.orderItems[0]
          product.value = {
            fruitId: item.fruitId,
            fruitName: item.fruitName,
            specifications: item.specifications || '',
            price: item.price,
            quantity: item.quantity,
            fruitImage: item.fruitImage,
            orderNo: order.orderNo,
            orderItemId: item.id
          }
          
          // 设置默认退款金额
          form.value.refundAmount = maxRefundAmount.value
          
          // 默认填充用户联系方式
          form.value.contact = order.receiverPhone || ''
        }
      }
    } catch (error) {
      console.error('获取订单详情失败', error)
      uni.showToast({
        title: '获取订单详情失败',
        icon: 'none'
      })
    } finally {
      loading.value = false
    }
  }
})

// 选择退款原因
const onReasonConfirm = (e) => {
  form.value.reason = e.value[0]
  showReasonPicker.value = false
}

// 上传图片
const afterRead = async (event) => {
  const { file } = event.detail
  
  // 实际项目中需要先上传到服务器获取URL
  try {
    // TODO: 上传图片到服务器
    // 这里模拟上传成功
    setTimeout(() => {
      form.value.images.push({
        url: file.url,
        status: 'success',
        message: '上传成功'
      })
    }, 300)
  } catch (error) {
    uni.showToast({
      title: '图片上传失败',
      icon: 'none'
    })
  }
}

// 删除图片
const deletePic = (event) => {
  const { index } = event.detail
  form.value.images.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  try {
    if (!isFormValid.value) {
      uni.showToast({
        title: '请完善表单信息',
        icon: 'none'
      })
      return
    }

    submitting.value = true
    
    // 准备提交数据
    const aftersaleDTO = {
      orderNo: product.value.orderNo,
      orderItemId: product.value.orderItemId,
      productId: product.value.fruitId,
      refundAmount: parseFloat(form.value.refundAmount),
      reason: form.value.reason,
      description: form.value.description,
      images: form.value.images.map(img => img.url),
      contactPhone: form.value.contact
    }
    
    // 调用提交API
    const res = await orderStore.submitAftersale(aftersaleDTO)
    
    if (res && res.code === 200) {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: res.message || '提交申请失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交申请失败', error)
    uni.showToast({
      title: '提交申请失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
}

.product-card {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  display: flex;
  align-items: center;

  .product-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
  }

  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 160rpx;

    .product-name {
      font-size: 28rpx;
      color: #333333;
    }

    .product-spec {
      font-size: 24rpx;
      color: #999999;
    }

    .product-price-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .product-price {
        font-size: 28rpx;
        color: #1890ff;
        font-weight: bold;
      }

      .product-quantity {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }
}

.form-card {
  margin: 20rpx;
  padding: 0 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;

  .form-item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .label {
      display: block;
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 20rpx;

      &.required::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 4rpx;
      }
    }

    .input-wrap {
      display: flex;
      align-items: center;
      height: 80rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 0 20rpx;

      .currency {
        font-size: 32rpx;
        color: #333333;
        margin-right: 10rpx;
      }

      .input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
      }

      .reason-text {
        flex: 1;
        font-size: 28rpx;
        color: #333333;

        &.placeholder {
          color: #999999;
        }
      }
    }

    .textarea {
      width: 100%;
      height: 200rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 20rpx;
      font-size: 28rpx;
    }

    .word-count {
      display: block;
      text-align: right;
      font-size: 24rpx;
      color: #999999;
      margin-top: 10rpx;
    }

    .upload-wrap {
      .upload-button {
        width: 160rpx;
        height: 160rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        text {
          font-size: 24rpx;
          color: #999999;
          margin-top: 10rpx;
        }
      }

      .upload-tip {
        display: block;
        font-size: 24rpx;
        color: #999999;
        margin-top: 20rpx;
      }
    }
  }
}

.submit-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  padding: 20rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .btn-submit {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
    color: #ffffff;
    border-radius: 40rpx;
    font-size: 28rpx;

    &:disabled {
      opacity: 0.6;
    }
  }
}
</style> 